/**
 * 
 */
package com.gwcloud.leetcode.offers;

/**
 * @ClassName   : Leetcode0530 
 * @author      : ganwei 
 * @date        : 2020年6月6日
 * @Description : Leetcode0530
 */
public class Leetcode0530 {
    /**
     * -二分查找
     */
	public int search(int[] nums, int target) {
		int index = search(nums, 0, nums.length-1, target);
    	if(index == -1){
    		return 0;
    	}
    	int count = 0;
    	int tmpindex = index;
    	while(tmpindex >= 0 && nums[tmpindex--] == target) count++;
    	tmpindex = index+1;
    	while(tmpindex < nums.length && nums[tmpindex++] == target) count++;
    	return count;
    }
	
	public int search(int[] nums, int start, int end, int target){
		
		while(start <= end){
			int mid = (start+end) / 2;
			if(nums[mid] == target){
				return mid;
			}else if(nums[mid] > target){
				end = mid - 1;
			}else{
				start = mid + 1;
			}
		}
		return -1;
	}
	/**
	 * -主函数
	 */
	public static void main(String[] args){
		int[] nums = {1,2,3,4,6};
		Leetcode0530 l0530 = new Leetcode0530();
		System.out.println(l0530.search(nums, 0, nums.length-1, 4));
	}
}
